<template>
  <div ref="chartRef" class="base-chart"></div>
</template>
<script setup lang="ts">
import echarts from '@/lib/echarts'

const chartRef = shallowRef()
const chartInstance = shallowRef()
let resizeObserver: any = null

interface EventType {
  eventName: string
  query?: string | Object
  handler: Function
  context?: Object
}

const props = defineProps({
  option: {
    type: Object,
    default: () => ({}),
  },
  events: {
    type: Array as PropType<EventType[]>,
    default: () => [],
  },
})

watch(
  () => props.option,
  () => {
    nextTick(() => {
      chartInstance.value?.setOption(props.option)
    })
  },
  { deep: true }
)

onMounted(initChart)

onBeforeUnmount(() => {
  resizeObserver?.disconnect()
  resizeObserver = null
  handleEvent('off')
  chartInstance.value?.dispose()
  chartInstance.value = null
})

function initChart() {
  chartInstance.value = echarts.init(chartRef.value)
  handleEvent('on')
  chartInstance.value.setOption(props.option)
  resizeObserver = new ResizeObserver(() => {
    nextTick(() => {
      chartInstance.value?.resize({
        animation: {
          duration: 200,
          easing: 'linear',
        },
      })
    })
  })
  resizeObserver.observe(chartRef.value, {
    attributeFilter: ['style'],
  })
}

//注册注销事件
function handleEvent(type: 'on' | 'off') {
  if (props.events.length) {
    props.events.forEach(item => {
      const args =
        type === 'on'
          ? [item.eventName, item.query, item.handler, item.context].filter(arg => arg)
          : [item.eventName]
      chartInstance.value?.[type](...args)
    })
  }
}

//暴露图表实例
defineExpose({
  chartInstance,
})
</script>
<style scoped lang="scss">
.base-chart {
  width: 100%;
  height: 100%;
}
</style>

<!-- useage
<BaseChart :option="option" :events="events" />

const events=[{eventName:'click',handler:(params)=>{}},...]
添加事件可选参数如下，具体参考echarts文档
  eventName: string
  query?: string | Object
  handler: Function
  context?: Object

更多功能可调用暴露出来的图表实例chartInstance
-->
